﻿/********************************************************
    * Project Name   : VAdvantage
    * Class Name     : InfoInvoice
    * Purpose        : search window for invoice
    * Class Used     : info
    * Chronological    Development
    * Raghunandan     15-Dec-2010
******************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VAdvantage.Classes;
using VAdvantage.Common;
using VAdvantage.Process;
using VAdvantage.Model;
using VAdvantage.DataBase;
using VAdvantage.SqlExec;
using VAdvantage.Utility;
using System.Windows.Forms;
using VAdvantage.Controls;
using System.Data;
using System.Data.SqlClient;
using VAdvantage.Framework;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Reflection;
using System.Windows.Media;


namespace VAdvantage.Search
{
    public partial class InfoInvoice : Info
    {
        #region private variable

        int bp;
        int order;
        private const int HEIGHT = 23;
        //on value change of datetime pickker
        private bool _dateTimeFromCheck = false;
        private bool _dateTimeToCheck = false;
        //on Amount text change value
        private bool _AmtFromCheck = false;
        private bool _AmtToCheck = false;
        //  Static Info
        private VLabel lblDocumentNo = new VLabel();
        private VLabel lblDescription = new VLabel();
        private VLabel lblBPartner_ID = new VLabel();
        private VLabel lblOrder_ID = new VLabel();
        private VLabel lblDateFrom = new VLabel();
        private VLabel lblDateTo = new VLabel();
        private VLabel lblAmtFrom = new VLabel();
        private VLabel lblAmtTo = new VLabel();

        private VTextBox txtDocumentNo = new VTextBox(HEIGHT);
        private VTextBox txtDescription = new VTextBox(HEIGHT);

        private VTextBoxButton vSearchBPartner;
        private VTextBoxButton vSearchOrder_ID;

        private VCheckBox chkIsPaid = new VCheckBox();
        private VCheckBox chkIsSOTrx = new VCheckBox();
        //

        private VAdvantage.Controls.VDatePicker dtpDateFrom = new VAdvantage.Controls.VDatePicker();
        private VAdvantage.Controls.VDatePicker dtpDateTo = new VAdvantage.Controls.VDatePicker();

        private VNumTextBox txtAmtFrom = new VNumTextBox();
        private VNumTextBox txtAmtTo = new VNumTextBox();
        //Array of Column Info   

        private static Info_Column[] _invoiceLayout = {
        new Info_Column("C_Invoice_ID", "i.C_Invoice_ID", typeof(IDColumn)),
        new Info_Column(Msg.Translate(Envs.GetContext(), "C_BPartner_ID").Replace("/"," Or "), "(SELECT Name FROM C_BPartner bp WHERE bp.C_BPartner_ID=i.C_BPartner_ID)", typeof(String)),
        new Info_Column(Msg.Translate(Envs.GetContext(), "DateInvoiced"), "i.DateInvoiced", typeof(DateTime)),
        new Info_Column(Msg.Translate(Envs.GetContext(), "DocumentNo"), "i.DocumentNo", typeof(String)),
        new Info_Column(Msg.Translate(Envs.GetContext(), "C_Currency_ID"), "(SELECT ISO_Code FROM C_Currency c WHERE c.C_Currency_ID=i.C_Currency_ID)", typeof(String)),
        new Info_Column(Msg.Translate(Envs.GetContext(), "GrandTotal"), "i.GrandTotal",  typeof(Decimal)),
        new Info_Column(Msg.Translate(Envs.GetContext(), "ConvertedAmount"), "currencyBase(i.GrandTotal, i.C_Currency_ID, i.DateAcct, i.AD_Client_ID, i.AD_Org_ID)", typeof(Decimal)),
        new Info_Column(Msg.Translate(Envs.GetContext(), "OpenAmt"), "invoiceOpen(C_Invoice_ID,C_InvoicePaySchedule_ID)", typeof(Decimal), true, true, null),
        new Info_Column(Msg.Translate(Envs.GetContext(), "IsPaid"), "i.IsPaid", typeof(Boolean)),
        new Info_Column(Msg.Translate(Envs.GetContext(), "IsSOTrx"), "i.IsSOTrx", typeof(Boolean)),
        new Info_Column(Msg.Translate(Envs.GetContext(), "Description"), "i.Description", typeof(String)),
        new Info_Column(Msg.Translate(Envs.GetContext(), "POReference"), "i.POReference", typeof(String)),
        new Info_Column("C_InvoicePaySchedule_ID", "''", typeof(KeyNamePair), "i.C_InvoicePaySchedule_ID")
    };

        string _queryValue = "";
        #endregion

        /// <summary>
        /// Detail Protected Contructor
        /// </summary>
        /// <param name="frame">form</param>
        /// <param name="modal">model</param>
        /// <param name="WindowNo">window no</param>
        /// <param name="value">query value</param>
        /// <param name="multiSelection">multiple selections</param>
        /// <param name="whereClause">where clause</param>
        public InfoInvoice(Object frame, bool modal, int WindowNo, String value, bool multiSelection, String whereClause)
            : base(frame, modal, WindowNo, "i", "C_Invoice_ID", multiSelection, whereClause)
        {
            base.SetTitle(Msg.GetMsg(Envs.GetContext(), "InfoInvoice", true));
            //
            try
            {
                _queryValue = value;
                StatInit();
                _LoadedOK = InitInfo();
            }
            catch
            {
                return;
            }

        }

        /// <summary>
        /// Get Layout
        /// </summary>
        /// <returns>array of Column_Info</returns>
        protected override Info_Column[] GetInfoColumns()
        {
            return _invoiceLayout;
        }

        /// <summary>
        /// Set InfoOrder Form LayOut by overriding base class design
        /// </summary>
        public override void Init()
        {
            InitializeComponent();
            base.outerPanel.Background = new SolidColorBrush(GlobalVariable.WINDOW_BACK_COLOR);
        }

        /// <summary>
        /// Static Setup - add fields to parameterPanel
        /// </summary>
        private void StatInit()
        {
            Lookup _value = null;
            Lookup _value1 = null;
            String _isSOTrxMsg = "";
            InfoSetting();

            SetBusy(true);
                
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                _value = MLookupFactory.Get(Envs.GetContext(), _WindowNo, 3499, DisplayType.Search);
                _value1 = MLookupFactory.Get(Envs.GetContext(), _WindowNo, 4247, DisplayType.Search);
                _isSOTrxMsg = Msg.GetElement(Envs.GetContext(), "IsSOTrx");
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => InvoKFunction(_value, _value1, _isSOTrxMsg));
            });

            lblDocumentNo.Content = Msg.Translate(Envs.GetContext(), "DocumentNo");
            lblDescription.Content = Msg.Translate(Envs.GetContext(), "Desscription");
            ////for kc
            //lblDescription.Content = Msg.Translate(Envs.GetContext(), "UnivRegNO/Roll No");
            //////
            lblOrder_ID.Content = Msg.Translate(Envs.GetContext(), "C_Order_ID");
            lblBPartner_ID.Content = Msg.Translate(Envs.GetContext(), "BPartner");
            lblDateFrom.Content = Msg.Translate(Envs.GetContext(), "DateInvoiced");
            lblDateTo.Content = "-";
            lblAmtFrom.Content = Msg.Translate(Envs.GetContext(), "GrandTotal");
            lblAmtTo.Content = "-";

            //tooltip.SetToolTip(chkIsSOTrx, Msg.GetElement(Envs.GetContext(), "IsSOTrx"));
            chkIsSOTrx.IsChecked = true;
            //check box2
            chkIsPaid.Content = Msg.Translate(Envs.GetContext(), "IsPaid");
            //tooltip.SetToolTip(chkIsPaid, Msg.Translate(Envs.GetContext(), "IsPaid"));
            chkIsPaid.IsChecked = false;

            //Level Controls alignment
            lblDocumentNo.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblDocumentNo.Margin = new Thickness(0, 0, 5, 0);

            lblDescription.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblDescription.Margin = new Thickness(0, 0, 5, 0);

            lblOrder_ID.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblOrder_ID.Margin = new Thickness(0, 0, 5, 0);

            lblBPartner_ID.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblBPartner_ID.Margin = new Thickness(0, 0, 5, 0);

            lblDateFrom.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblDateFrom.Margin = new Thickness(0, 0, 5, 0);

            lblDateTo.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblDateTo.Margin = new Thickness(0, 0, 5, 0);

            lblAmtFrom.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblAmtFrom.Margin = new Thickness(0, 0, 5, 0);

            lblAmtTo.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblAmtTo.Margin = new Thickness(0, 0, 5, 0);

            chkIsSOTrx.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            chkIsSOTrx.Margin = new Thickness(0, 0, 5, 0);

            chkIsPaid.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            chkIsPaid.Margin = new Thickness(0, 0, 5, 0);

            //Document NO
            Grid.SetRow(lblDocumentNo, 0);
            Grid.SetColumn(lblDocumentNo, 0);
            this.tablePanel.Children.Add(lblDocumentNo);

            txtDocumentNo.Height = HEIGHT;
            txtDocumentNo.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            Grid.SetRow(txtDocumentNo, 0);
            Grid.SetColumn(txtDocumentNo, 1);
            this.tablePanel.Children.Add(txtDocumentNo);

            //Business Partners
            Grid.SetRow(lblBPartner_ID, 0);
            Grid.SetColumn(lblBPartner_ID, 2);
            this.tablePanel.Children.Add(lblBPartner_ID);

            //Chek box for sales transaction 
            Grid.SetRow(chkIsSOTrx, 0);
            Grid.SetColumn(chkIsSOTrx, 5);
            this.tablePanel.Children.Add(chkIsSOTrx);

            //Chek box for paid
            Grid.SetRow(chkIsPaid, 0);
            Grid.SetColumn(chkIsPaid, 6);
            this.tablePanel.Children.Add(chkIsPaid);

            //Description
            Grid.SetRow(lblDescription, 1);
            Grid.SetColumn(lblDescription, 0);
            this.tablePanel.Children.Add(lblDescription);

            txtDescription.Height = HEIGHT;
            Grid.SetRow(txtDescription, 1);
            Grid.SetColumn(txtDescription, 1);
            this.tablePanel.Children.Add(txtDescription);

            //date Ordered(Date From)
            Grid.SetRow(lblDateFrom, 1);
            Grid.SetColumn(lblDateFrom, 2);
            this.tablePanel.Children.Add(lblDateFrom);

            dtpDateFrom.Height = HEIGHT;
            Grid.SetRow(dtpDateFrom, 1);
            Grid.SetColumn(dtpDateFrom, 3);
            this.tablePanel.Children.Add(dtpDateFrom);

            //Date to
            Grid.SetRow(lblDateTo, 1);
            Grid.SetColumn(lblDateTo, 4);
            this.tablePanel.Children.Add(lblDateTo);

            dtpDateTo.Height = HEIGHT;
            Grid.SetRow(dtpDateTo, 1);
            Grid.SetColumn(dtpDateTo, 5);
            this.tablePanel.Children.Add(dtpDateTo);

            //Order

            Grid.SetRow(lblOrder_ID, 2);
            Grid.SetColumn(lblOrder_ID, 0);
            this.tablePanel.Children.Add(lblOrder_ID);

            //Grand Total(Amount From)
            Grid.SetRow(lblAmtFrom, 2);
            Grid.SetColumn(lblAmtFrom, 2);
            this.tablePanel.Children.Add(lblAmtFrom);

            txtAmtFrom.Height = HEIGHT;
            Grid.SetRow(txtAmtFrom, 2);
            Grid.SetColumn(txtAmtFrom, 3);
            this.tablePanel.Children.Add(txtAmtFrom);

            //Amount to
            Grid.SetRow(lblAmtTo, 2);
            Grid.SetColumn(lblAmtTo, 4);
            this.tablePanel.Children.Add(lblAmtTo);

            txtAmtTo.Height = HEIGHT;
            Grid.SetRow(txtAmtTo, 2);
            Grid.SetColumn(txtAmtTo, 5);
            this.tablePanel.Children.Add(txtAmtTo);




            //key event handling only on text boexes
            txtDocumentNo.KeyDown += new KeyEventHandler(KeyEvents);
            txtDescription.KeyDown += new KeyEventHandler(KeyEvents);
            //txtAmtFrom.KeyDown += new KeyEventHandler(KeyEvents);
            // txtAmtTo.KeyDown += new KeyEventHandler(KeyEvents);
            this.chkIsSOTrx.Checked += new RoutedEventHandler(chkIsSOTrx_CheckedChanged);
            this.chkIsSOTrx.Unchecked += new RoutedEventHandler(chkIsSOTrx_CheckedChanged);

            this.chkIsPaid.Checked += new RoutedEventHandler(chkIsPaid_CheckedChanged);
            this.chkIsPaid.Unchecked += new RoutedEventHandler(chkIsPaid_CheckedChanged);

            //this.dtpDateFrom.ValueChanged += new System.EventHandler(this.dtpDateFrom_ValueChanged);
            //this.dtpDateTo.ValueChanged += new System.EventHandler(this.dtpDateTo_ValueChanged);
            this.dtpDateFrom.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(dtpDateFrom_SelectedDateChanged);
            this.dtpDateTo.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(dtpDateTo_SelectedDateChanged);

            this.txtAmtFrom.TextChanged += new TextChangedEventHandler(txtAmtFrom_TextChanged);
            this.txtAmtTo.TextChanged += new TextChangedEventHandler(txtAmtTo_TextChanged);
            txtDocumentNo.TextChanged += new TextChangedEventHandler(txtDocumentNo_TextChanged);
            txtDescription.TextChanged += new TextChangedEventHandler(txtDescription_TextChanged);
            vdgvRecords.AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(vdgvRecords_AutoGeneratingColumn);

        }


        private void InvoKFunction(Lookup _value, Lookup _value1, String _isSOTrxMsg)
        {

            vSearchBPartner = new VTextBoxButton("C_BPartner_ID", false, false, true, DisplayType.Search, _value);
            vSearchOrder_ID = new VTextBoxButton("C_Order_ID", false, false, true, DisplayType.Search, _value1);
            //check box1
            chkIsSOTrx.Content = _isSOTrxMsg;


            Grid.SetRow(vSearchBPartner, 0);
            Grid.SetColumn(vSearchBPartner, 3);
            this.tablePanel.Children.Add(vSearchBPartner);

            Grid.SetRow(vSearchOrder_ID, 2);
            Grid.SetColumn(vSearchOrder_ID, 1);
            this.tablePanel.Children.Add(vSearchOrder_ID);

            Context ctx = Envs.GetContext();
            String bp = ctx.GetContext(_WindowNo, "C_BPartner_ID");
            if (bp != null && bp.Length != 0)
            {
                vSearchBPartner.SetValue(bp);
            }

            var count = 0;
            if (vdgvRecords.ItemsSource != null)
            {
                count = vdgvRecords.ItemsSource.OfType<object>().Count();
            }
            base.SetStatusMsg(count.ToString() + " " + Msg.GetMsg(Envs.GetContext(), "SearchRows_EnterQuery", true));
            if (_queryValue != null && _queryValue.Length > 0)
            {
                txtDocumentNo.Text = _queryValue.ToString();
                ExecuteQuery();
            }
            txtDocumentNo.Focus();
            SetBusy(false);
        }

        /// <summary>
        /// Sets the display setting
        /// </summary>
        protected void InfoSetting()
        {
            RowDefinition row = new RowDefinition();
            row.Height = new GridLength(0, GridUnitType.Auto);
            row.MinHeight = 30;
            this.tablePanel.RowDefinitions.Add(row);

            row = new RowDefinition();
            row.Height = new GridLength(0, GridUnitType.Auto);
            row.MinHeight = 30;
            this.tablePanel.RowDefinitions.Add(row);

            row = new RowDefinition();
            row.Height = new GridLength(0, GridUnitType.Auto);
            row.MinHeight = 30;
            this.tablePanel.RowDefinitions.Add(row);


            ColumnDefinition column = new ColumnDefinition();
            column.Width = new GridLength(25, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(45, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(25, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(45, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(25, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(45, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(35, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            //parameter panel   
            //CommonFunctions.SetDataGridPrperties(vdgvRecords);
        }

        /// <summary>
        /// General Init
        /// </summary>
        /// <returns>true, if success</returns>
        private bool InitInfo()
        {
            //writen in invock function
            //  Set Defaults
            //Context ctx = Envs.GetContext();
            //String bp = ctx.GetContext(_WindowNo, "C_BPartner_ID");
            //if (bp != null && bp.Length != 0)
            //{
            //    vSearchBPartner.SetValue(bp);
            //}

            //  prepare table
            StringBuilder where = new StringBuilder("i.IsActive='Y'");
            if (_whereClause.Length > 0)
            {
                where.Append(" AND ").Append(Util.Replace(_whereClause, "C_Invoice.", "i."));
            }
            PrepareTable("C_Invoice_v i",   //  corrected for CM
                where.ToString(),
                "2,3,4");
            return true;
        }

        string docNo = "";
        string disc = "";
        object bPartner = null;
        object orderSearch = null;
        System.DateTime? dFrom = null;
        System.DateTime? dTo = null;
        string textAmountfrom = "";
        string textAmountTo = "";
        bool paid = false;
        bool trxchek = false;

        /// <summary>
        /// Construct SQL Where Clause and define parameters.
        /// (setParameters needs to set parameters)
        /// Includes first AND
        /// </summary>
        /// <returns>sql</returns>
        public override String GetSQLWhere()
        {

            //Dispatcher.BeginInvoke(delegate() { docNo = txtDocumentNo.Text; });
            StringBuilder sql = new StringBuilder();
            if (docNo.Length > 0)
            {
                sql.Append(" AND UPPER(i.DocumentNo) LIKE @param1");
                //sql.Append(" AND UPPER(i.DocumentNo) LIKE '" + docNo + "'");
            }
            //Dispatcher.BeginInvoke(delegate() { disc = txtDescription.Text; });
            if (disc.Length > 0)
            {
                sql.Append(" AND UPPER(i.Description) LIKE @param2");
                //sql.Append(" AND UPPER(i.Description) LIKE '" + disc + "'");
            }
            // Dispatcher.BeginInvoke(delegate() { bPartner = vSearchBPartner.GetValue(); });
            if (bPartner != null && bPartner != DBNull.Value)
            {
                sql.Append(" AND i.C_BPartner_ID=@param3");
                // sql.Append(" AND i.C_BPartner_ID=" + bPartner);
            }
            //Dispatcher.BeginInvoke(delegate() { orderSearch = vSearchOrder_ID.GetValue(); });
            if (orderSearch != null && orderSearch != DBNull.Value)
            {
                sql.Append(" AND i.C_Order_ID=@param4");
                //sql.Append(" AND i.C_Order_ID=" + orderSearch);
            }
            //Dispatcher.BeginInvoke(delegate() { dFrom = dtpDateFrom.Text.Trim(); });
            //Dispatcher.BeginInvoke(delegate() { dTo = dtpDateTo.Text.Trim(); });
            if ((dFrom != null || dTo != null))
            {
                //if (dFrom.Value.ToString() != "" || dTo.Value.ToString() != "")
                {
                    if (!_dateTimeFromCheck && _dateTimeToCheck)
                    {
                        sql.Append(" AND TRUNC(i.DateInvoiced,'DD') <= @param6");
                        // sql.Append(" AND TRUNC(i.DateInvoiced,'DD') <= '" + dTo + "'");
                    }
                    else if (_dateTimeFromCheck && !_dateTimeToCheck)
                    {
                        sql.Append(" AND TRUNC(i.DateInvoiced,'DD') >= @param5");
                        //sql.Append(" AND TRUNC(i.DateInvoiced,'DD') >= '" + dFrom + "'");
                    }
                    else if (_dateTimeFromCheck && _dateTimeToCheck)
                    {
                        sql.Append(" AND TRUNC(i.DateInvoiced,'DD') BETWEEN @param5 AND @param6");
                        //sql.Append(" AND TRUNC(i.DateInvoiced,'DD') BETWEEN '" + dFrom + "' AND '" + dTo + "'");
                    }
                }
            }
            //Dispatcher.BeginInvoke(delegate() { textAmountfrom = txtAmtFrom.Text.Trim(); });
            //Dispatcher.BeginInvoke(delegate() { textAmountTo = txtAmtTo.Text.Trim(); });
            if (textAmountfrom != null || textAmountTo != null)
            {
                //this is for default text in the number text box
                if (textAmountfrom == "0" && textAmountTo == "0")
                {

                }
                else
                {
                    Decimal grantAmtFrom = Util.GetValueOfDecimal(textAmountfrom);
                    Decimal grantAmtTo = Util.GetValueOfDecimal(textAmountTo);
                    if (!_AmtToCheck && _AmtFromCheck)
                    {
                        sql.Append(" AND i.GrandTotal >= @param7");
                        //sql.Append(" AND i.GrandTotal >= " + grantAmtFrom);
                    }
                    else if (!_AmtFromCheck && _AmtToCheck)
                    {
                        sql.Append(" AND i.GrandTotal <= @param8");
                        //sql.Append(" AND i.GrandTotal <= " + grantAmtTo);
                    }
                    else if (_AmtFromCheck && _AmtToCheck)
                    {
                        sql.Append(" AND i.GrandTotal BETWEEN @param7 AND @param8");
                        // sql.Append(" AND i.GrandTotal BETWEEN " + grantAmtFrom + " AND " + grantAmtTo);
                    }

                }
            }

            //Dispatcher.BeginInvoke(delegate() { paid = (bool)chkIsPaid.IsChecked; });
            //Dispatcher.BeginInvoke(delegate() { trxchek = (bool)chkIsSOTrx.IsChecked; });

            String chekPaid = paid ? "Y" : "N";
            String checkTrx = trxchek ? "Y" : "N";
            sql.Append(" AND i.IsPaid=" + "'" + chekPaid + "'" + " AND i.IsSOTrx=" + "'" + checkTrx + "'");
            //	//log.fine( "InfoInvoice.setWhereClause", sql.toString());
            return sql.ToString();
        }

        /// <summary>
        /// Set Parameters for Query.
        /// (as defined in getSQLWhere)
        /// </summary>
        /// <param name="param">statement</param>
        /// <param name="forCount">for counting records</param>
        public override void SetParameters(out SqlParameter[] param, bool forCount)
        {
            String documentNo = GetSQLText(docNo);
            String des = GetSQLText(disc);
            //String orderRef = GetSQLText(vSearchOrder_ID);

            Decimal grantAmtFrom = Util.GetValueOfDecimal(textAmountfrom);
            Decimal grantAmtTo = Util.GetValueOfDecimal(textAmountTo);
            bp = 0;
            if (bPartner != null)
            {
                bp = Convert.ToInt32(bPartner);
            }

            //
            if (orderSearch != null)
            {
                order = Convert.ToInt32(orderSearch);
                //log.fine("Order=" + order);
            }
            int paramcount = 0;
            if (!(documentNo.Equals("") || documentNo.Equals("%")))
            {
                paramcount++;
            }
            if (!(des.Equals("") || des.Equals("%")))
            {
                paramcount++;
            }
            if (!(bp.Equals("") || bp.Equals("%") || bp == 0))
            {
                paramcount++;
            }
            if (!(order.Equals("") || order.Equals("%") || order == 0))
            {
                paramcount++;
            }
            //becouse this contain default date
            //if (!(orderDateFrom.Equals("") || orderDateFrom.Equals("%")))
            if (_dateTimeFromCheck)
            {
                paramcount++;
            }
            //if (!(orderDateTo.Equals("") || orderDateTo.Equals("%")))
            if (_dateTimeToCheck)
            {
                paramcount++;
            }
            if (textAmountfrom == "0" && textAmountTo == "0")
            {
            }
            else
            {
                if (_AmtFromCheck)
                {
                    paramcount++;
                }
                if (_AmtToCheck)
                {
                    paramcount++;
                }
            }


            param = new SqlParameter[paramcount];
            int index = 0;
            //	=> Documenet Number
            if (!(documentNo.Equals("") || documentNo.Equals("%")))
            {
                if (!documentNo.EndsWith("%"))
                {
                    documentNo += "%";
                }
                param[index++] = new SqlParameter("@param1", documentNo);
            }
            //	=> DEscription
            if (!(des.Equals("") || des.Equals("%")))
            {
                if (!des.EndsWith("%"))
                {
                    des += "%";
                }
                param[index++] = new SqlParameter("@param2", des);
            }
            //	=> Busness Partner
            if (!(bp.Equals("") || bp.Equals("%") || bp == 0))
            {
                param[index++] = new SqlParameter("@param3", bp);
            }
            //	=> Order Refrence
            if (!(order.Equals("") || order.Equals("%") || order == 0))
            {
                param[index++] = new SqlParameter("@param4", order);
            }
            if ((dFrom != null || dTo != null))
            {
                //if (dFrom.Value.ToString() != "" || dTo.Value.ToString() != "")
                {
                    //	=> Date Ordered From
                    if (_dateTimeFromCheck)
                    {
                        param[index++] = new SqlParameter("@param5", dFrom.Value.ToString("dd-MMM-yy"));
                    }
                    //	=> Date Ordered TO
                    if (_dateTimeToCheck)
                    {
                        param[index++] = new SqlParameter("@param6", dTo.Value.ToString("dd-MMM-yy"));
                    }
                }
            }
            if (textAmountfrom == "0" && textAmountTo == "0")
            {
            }
            else
            {
                //	=> amount from
                if (_AmtFromCheck)
                {
                    param[index++] = new SqlParameter("@param7", grantAmtFrom);
                }
                //	=> Date Amt to
                if (_AmtToCheck)
                {
                    param[index++] = new SqlParameter("@param8", grantAmtTo);
                }
            }
        }

        /// <summary>
        /// Get SQL WHERE parameter
        /// </summary>
        /// <param name="f">field</param>
        /// <returns>sql</returns>
        private String GetSQLText(string f)
        {
            String s = f.ToString().Trim().ToUpper();
            if (!s.EndsWith("%"))
            {
                s += "%";
            }
            //log.fine("String=" + s);
            return s;
        }

        /// <summary>
        /// Zoom
        /// </summary>
        void Zoom()
        {
            log.Info("InfoInvoice.zoom");
            int C_Invoice_ID = Convert.ToInt32(GetSelectedRowKey());
            if (C_Invoice_ID == null)
            {
                return;
            }
            Query query = new Query("C_Invoice");
            query.AddRestriction("C_Invoice_ID", Query.EQUAL, C_Invoice_ID);
            query.SetRecordCount(1);
            int AD_WindowNo = GetAD_Window_ID("C_Invoice", (bool)chkIsSOTrx.IsChecked);
            //Zoom(AD_WindowNo, query);
        }

        /// <summary>
        /// Has Zoom
        /// </summary>
        /// <returns>true</returns>
        bool HasZoom()
        {
            return true;
        }

        /// <summary>
        /// On key down event
        /// </summary>
        /// <param name="sender">key</param>
        /// <param name="e">current event</param>
        private void KeyEvents(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                ExecuteQuery();
            }
            else if (e.Key == Key.Down)
            {
                vdgvRecords.Focus();
            }
        }

        /// <summary>
        /// Save Selection Settings
        /// </summary>
        public override void SaveSelectionDetail()
        {
            int INDEX_PAYSCHEDULE = _invoiceLayout.Length - 1;	//	last item
            //  publish for Callout to read
            Context ctx = Envs.GetContext();
            int ID = Convert.ToInt32(GetSelectedRowKey());
            ctx.SetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "C_Invoice_ID", ID == null ? "0" : ID.ToString());
            int C_InvoicePaySchedule_ID = 0;
            //int row = p_table.getSelectedRow();
            int row = vdgvRecords.SelectedItems.Count;

            if (row == 1)
            {
                row = 0;
            }

            if (row >= 0)
            {
                if (vdgvRecords.SelectedItem != null)
                {
                    var type = vdgvRecords.SelectedItem.GetType();
                    PropertyInfo objPropInfo = type.GetProperty(_Layout[INDEX_PAYSCHEDULE].GetColHeader());
                    if (objPropInfo != null)
                    {
                        Object data = objPropInfo.GetValue(vdgvRecords.SelectedItem, null);
                        if (data.GetType() == typeof(KeyNamePair))
                            C_InvoicePaySchedule_ID = ((KeyNamePair)data).GetKey();
                    }
                }
            }
            if (C_InvoicePaySchedule_ID <= 0)	//	not selected
            {
                ctx.SetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "C_InvoicePaySchedule_ID", "0");
            }
            else
            {
                ctx.SetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "C_InvoicePaySchedule_ID", C_InvoicePaySchedule_ID.ToString());
            }
        }

        /// <summary>
        /// Check Click event to show records in grid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkIsSOTrx_CheckedChanged(object sender, RoutedEventArgs e)
        {
            paid = (bool)chkIsPaid.IsChecked;
            trxchek = (bool)chkIsSOTrx.IsChecked;
            bPartner = vSearchBPartner.GetValue();
            orderSearch = vSearchOrder_ID.GetValue();
            ExecuteQuery();
        }

        /// <summary>
        /// chek paid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkIsPaid_CheckedChanged(object sender, RoutedEventArgs e)
        {
            paid = (bool)chkIsPaid.IsChecked;
            trxchek = (bool)chkIsSOTrx.IsChecked;
            bPartner = vSearchBPartner.GetValue();
            orderSearch = vSearchOrder_ID.GetValue();
            ExecuteQuery();
        }

        void dtpDateTo_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            _dateTimeToCheck = true;
            if (dtpDateTo.Text.Trim() != "")
            {
                dTo = Convert.ToDateTime(dtpDateTo.Text.Trim());
            }
            else
            {
                dTo = null;
            }
        }

        void dtpDateFrom_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            _dateTimeFromCheck = true;
            if (dtpDateFrom.Text.Trim() != "")
            {
                dFrom = Convert.ToDateTime(dtpDateFrom.Text.Trim());
            }
            else
            {
                dFrom = null;
            }
        }

        void txtAmtTo_TextChanged(object sender, TextChangedEventArgs e)
        {
            _AmtToCheck = true;
            textAmountTo = txtAmtTo.Text.Trim();
        }

        void txtAmtFrom_TextChanged(object sender, TextChangedEventArgs e)
        {
            _AmtFromCheck = true;
            textAmountfrom = txtAmtFrom.Text.Trim();

        }

        void txtDescription_TextChanged(object sender, TextChangedEventArgs e)
        {
            disc = txtDescription.Text;
        }

        void txtDocumentNo_TextChanged(object sender, TextChangedEventArgs e)
        {
            docNo = txtDocumentNo.Text;
        }

        protected override void bRefresh_Click(object sender, RoutedEventArgs e)//: base.VRefresh_Click(object sender, EventArgs e)
        {
            paid = (bool)chkIsPaid.IsChecked;
            trxchek = (bool)chkIsSOTrx.IsChecked;
            bPartner = vSearchBPartner.GetValue();
            orderSearch = vSearchOrder_ID.GetValue();
            ExecuteQuery();
        }

        void vdgvRecords_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            foreach (DataGridColumn col in vdgvRecords.Columns)
            {
                if (col.DisplayIndex == 0 || col.DisplayIndex == 12)
                {
                    col.Visibility = Visibility.Collapsed;
                }
            }
        }
    }
}
